<template>
	<view class="group-detail" v-if="groupInfo.ownInfo">
		<!-- 2. 成员列表（最多19人，横向滚动） -->
		<!-- 2. 成员列表（最终完整版本） -->
		<view class="member-list">
			<view class="member-container">
				<!-- 成员项 -->
				<view class="member-item"  v-for="(member, index) in displayMembers" :key="index" @click="userDetail(member.userId)">
					<view class="avatar">
						<avatar-fallback v-if="!member.nicPic" :size="50" :name="member.nicName"></avatar-fallback>
						<image v-else :src="member.nicPic" mode="cover"></image>
					</view>
					<view class="member-name">{{ member.nicName || '未知成员' }}</view>
					<view v-if="isDel" class="del-icon" @click.stop="delMember(member.userId)">
						<uni-icons type="closeempty" color="#fff"></uni-icons>
					</view>
				</view>

				<!-- 显示更多/收起按钮 -->
				<view v-if="needShowMore" class="member-item" @click="toggleShowAll">
					<view class="avatar more-avatar">
						<text class="more-text">{{ showAllMembers ? '收起' : '更多' }}</text>
					</view>
					<view class="member-name">
						{{ showAllMembers ? '收起' : `还有${this.members.length - 19}人` }}
					</view>
				</view>

				<!-- 添加成员按钮 -->
				<view class="add-member" @click="addMember">
					<view class="add-icon">+</view>
					<view class="add-text">添加成员</view>
				</view>
				<view class="add-member" v-if="isOwn" @click="handleDelMember">
					<view class="add-icon">-</view>
					<view class="add-text">删除成员</view>
				</view>
			</view>
			<!-- 成员总数 -->
			<view class="member-count" v-if="groupInfo.groupUser">{{ groupInfo.groupUser.length || 0 }}名成员</view>
		</view>

		<!-- 3. 群信息区域 -->
		<view class="group-info">
			<!-- 群名称 -->
			<view class="info-item" @click="editGroupName">
				<view class="info-label">群名称</view>
				<view class="info-value">{{ groupInfo.groupName || '未命名群聊' }}</view>
				<uni-icons type="right" size="16" color="#ccc" />
			</view>

			<!-- 群二维码 -->
			<view class="info-item" @click="showQrcode">
				<view class="info-label">群二维码</view>
				<view class="info-value">点击查看</view>
				<uni-icons type="right" size="16" color="#ccc" />
			</view>

			<!-- 群公告 -->
			<view class="info-item" @click="editNotice">
				<view class="info-label">群公告</view>
				<view class="info-value notice-value">{{ groupInfo.signature || '暂无公告' }}</view>
				<uni-icons type="right" size="16" color="#ccc" />
			</view>
		</view>

		<!-- 4. 功能操作区 -->
		<view class="function-area">
			<view class="function-item" @click="setSound">
				<image class="funtion-item-icon" :src="soundState.url" mode="aspectFill"></image>
				<view class="function-name">{{ soundState.value }}</view>
			</view>
			<view class="function-item" @click="clearChat">
				<uni-icons type="trash" size="20" color="#666" />
				<view class="function-name">清空聊天记录</view>
			</view>
			<view class="function-item" v-if="isOwn" @click="groupManager">
				<uni-icons type="gear" size="20" color="#666" />
				<view class="function-name">群使用须知</view>
			</view>
		</view>

		<!-- 5. 底部退出按钮 -->
		<view class="exit-btn" @click="confirmExit">{{ isOwn ? '解散本群' : '退出群聊' }}</view>

		<!-- 群二维码弹窗 -->
		<uni-popup ref="qrcodePopup" type="center">
			<view class="qrcode-popup">
				<view class="qrcode-title">群聊二维码</view>
				<view class="qrcode-content">
					<uv-qrcode ref="qrcode" :start="true" fileType="png" :auto="true" :value="groupInfo.groupId"></uv-qrcode>
				</view>
				<view class="qrcode-desc">扫码加入群聊</view>
				<view class="qrcode-close" @click="closeQrcode">关闭</view>
			</view>
		</uni-popup>

		<!-- 退出确认弹窗 -->

		<uni-popup ref="exitPopup" type="dialog">
			<uni-popup-dialog
				type="warning"
				cancelText="取消"
				confirmText="确定"
				:title="isOwn ? '解散本群' : '退出群聊'"
				:content="isOwn ? '确定要解散该群聊吗？解散后所有记录将丢失' : '退出群聊后，所以记录将无法保留'"
				@confirm="exitGroup"
				@close="dialogClose"
			></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref='readMe'>
			<view class="readMe">
			<rich-text :nodes="readMe">
			 
			</rich-text>
				
			</view>
		</uni-popup>
	</view>
</template>

<script>
const group = uniCloud.importObject('groupManager', { customUI: true });
import getFriendUserInfo from '../../utils/getFriendUserInfo';
import AvatarFallback from '../../components/AvatarFallback.vue';
import soundManger from '../../utils/soundManger';
import { storageUtil } from '../../utils/storageUtil.js';
export default {
	components: {
		AvatarFallback
	},
	data() {
		return {
			// 群信息（从接口获取）
			members: [],
			groupInfo: {},
			groupId: '',
			showAllMembers: false,
			delMemberId: '',
			isDel: false,
			sound: 2,
			readMe:` <h1 style="text-align:center;font-size:18px; margin: 16px 0;">群主权责</h1>
			  <p style="font-size: 15px; margin: 8px 0;">
			    <strong>一、群主特权</strong>
			  </p>
			  <ol style="margin: 8px 0; padding-left: 24px; line-height: 1.8;">
			    <li>设置入群规则</li>
			    <li>对成员进行禁言操作</li>
			    <li>删除违规成员</li>
			    <li>查看群员发言位置</li>
			    <li>查看群员联系电话</li>
			  </ol>
			  <p style="font-size: 15px; margin: 16px 0;">
			    <strong>二、群主责任</strong>
			  </p>
			  <ol style="margin: 8px 0; padding-left: 24px; line-height: 1.8;">
			    <li>对群成员发言承担监督责任</li>
			    <li>严禁发布违反法律法规的言论</li>
			    <li>严禁发布有违公序良俗的内容</li>
			    <li>不得利用群主身份泄露成员个人信息</li>
			  </ol>`
		};
	},
	computed: {
		// 显示的成员列表（最多19人）
		showMembers() {
			const { members } = this.groupInfo;
			return members.slice(0, 19); // 截取前19名成员
		},
		user() {
			return this.$store.state.msg.user;
		},
		isOwn() {
			return this.$store.state.msg.user.userId === this.groupInfo.ownInfo.userId;
		},
		soundState() {
			const sound = new soundManger();

			const state = sound.getState(this.groupInfo.groupId);
			console.log('状态', state);
			if (state === 2) {
				return { url: '/static/sound.png', value: '消息声音' };
			} else if (state === 0) {
				return { url: '/static/nosound.png', value: '消息静音' };
			} else if (state === 1) {
				return { url: '/static/vibration.png', value: '消息振动' };
			} else {
				return { url: '/static/sound.png', value: '消息声音' };
			}
		},
		displayMembers() {
			const totalMembers = this.members.length;
			// 未超过19人：显示全部；超过19人：根据状态切换
			if (totalMembers <= 19 || this.showAllMembers) {
				return this.members;
			}
			// 仅显示前19人（群主在第一位）
			return this.members.slice(0, 19);
		},
		needShowMore() {
			return this.members.length > 19;
		}
	},
	onLoad(res) {
		console.log(res);
		if (res?.id) {
			this.groupId = res.id;
		}
	},
	onShow() {
		if (!this.groupId) {
			uni.showToast({
				title: '群不存在',
				position: 'center'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 2000);
		}
		this.getGroupInfo(this.groupId);
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		setSound() {
			this.sound++;
			const soundmanger = new soundManger();
			const sound = this.sound % 3;
			soundmanger.setState(this.groupInfo.groupId, sound);
		},
		handleDelMember() {
			this.isDel = !this.isDel;
		},
		async delMember(id) {
			console.log('11111', id);
			if (this.groupInfo.ownInfo.userId !== this.user.userId) {
				uni.showToast({
					title: '非群主无权删除',
					icon: 'fail'
				});
				return;
			}
			if (id === this.user.userId) {
				uni.showToast({
					title: '不能删除群主',
					position: 'center'
				});
				return;
			}
			try {
				const res = await group.kickUser(this.user.userId, { groupId: this.groupInfo.groupId, clientId: id });
				if (res.code === 0) {
					uni.showToast({ title: '成员删除成功' });
					await this.getGroupInfo(this.groupId); // 重新获取群信息，保证数据最新
					this.isDel = false; // 退出删除模式
				} else {
					uni.showToast({ title: res.message || '删除失败', icon: 'none' });
				}
			} catch (e) {
				console.error('删除成员失败：', e);
				uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
			}
		},

		/**
		 * 异步获取群信息及成员列表
		 * @param {string} id - 群ID
		 */
		async getGroupInfo(id) {
			try {
				const res = await group.getGroupBygroupId(this.user.userId, { groupId: id });
				console.log('群', res);

				if (res.code) {
					this.groupInfo = res.data || {};

					const ownRes = res.data.ownInfo || {};
					const groupUsers = res.data.groupUser || [];
					console.log('成员', groupUsers);
					const memberPromises = groupUsers.map(async (item) => {
						try {
							if(!item.userId) console.warn('非法',item.userId);
							return await getFriendUserInfo(item.userId, this.user.userId);
						} catch (userErr) {
							console.error(`获取群成员 ${item.userId} 信息失败:`, userErr);
							return {
								nicName: '未知成员',
								nicPic: '', // 不提供头像，由UI处理
								userId: item.userId
							};
						}
					});

					// 等待所有成员信息请求完成，得到实际的成员数组
					const members = await Promise.all(memberPromises);
					console.log('格式化的成员', members);
					// 4. 构建群主信息对象
					const own = {
						nicName: `${ownRes.nicName || '群主'}(群主)`, // 更清晰的拼接逻辑
						nicPic: ownRes.nicPic?.url || '', // 使用可选链操作符安全访问
						userId: ownRes.userId || this.user.userId // 使用群主自己的ID
					};
					const filtered = members.filter((item) => item.userId !== this.user.userId);
					this.members = [own, ...filtered];
				} else {
					// 接口返回失败（如群已解散）
					uni.showToast({
						title: '群已解散或不存在',
						icon: 'fail'
					});
					// 延迟返回，让用户看到提示
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			} catch (e) {
				// 捕获整个函数执行过程中的任何错误（如网络错误）
				console.error('获取群信息失败:', e);
				uni.showToast({
					title: '获取群信息失败',
					icon: 'fail'
				});
			}
		},

		userDetail(id) {
			uni.navigateTo({
				url: `/pages/friend/friend?id=${id}`
			});
		},
		// 添加成员
		addMember() {
			if (!this.groupInfo?.groupId) {
				return;
			}
			uni.navigateTo({
				url: `/pages/contactPage/contactPage?type=applyGroup&groupId=${this.groupInfo.groupId}`
			});
		},

		// 编辑群名称
		editGroupName() {
			if (this.groupInfo.ownInfo.userId === this.user.userId) {
				uni.showModal({
					title: '修改群名称',
					editable: true,
					placeholderText: '请输入群名称',
					success: async (res) => {
						console.log(res);
						if (res.confirm && res.content) {
							this.groupInfo.groupName = res.content;
							try {
								const result = await group.editGroupName(this.user.userId, { groupId: this.groupId, newGroupName: res.content });
								console.log(result);
								if (result.code === 0) {
									this.getGroupInfo(this.groupId);
									uni.$emit('reload')
								}
							} catch (e) {
								console.error(e);
							}
						}
					}
				});
			} else {
				uni.showToast({
					title: '只有群主可改名称',
					position: 'center',
					duration: 2000
				});
			}
		},

		// 查看群二维码
		showQrcode() {
			this.$refs.qrcodePopup.open();
		},

		// 关闭二维码弹窗
		closeQrcode() {
			this.$refs.qrcodePopup.close();
		},

		// 编辑群公告
		editNotice() {
		
		},

	// 清空聊天记录
	clearChat() {
	  uni.showModal({
	    title: '提示',
	    content: '确定要清空聊天记录吗？此操作不可恢复',
	    success: (res) => {
	      if (res.confirm) {
	        storageUtil.removeByPrefix(`msg_group_${this.groupId}`);
	        uni.showToast({ title: '聊天记录已清空' }); // 仅提示，不跳转
	      }
	    }
	  });
	},
		toggleShowAll() {
			this.showAllMembers = !this.showAllMembers;
			// 优化体验：显示全部后自动滚动到最后一位成员
			if (this.showAllMembers) {
				setTimeout(() => {
					uni.createSelectorQuery()
						.in(this)
						.select('.member-container')
						.boundingClientRect((rect) => {
							if (rect) {
								// 滚动到容器底部
								uni.pageScrollTo({
									scrollTop: rect.bottom - rect.top - 200,
									duration: 300
								});
							}
						})
						.exec();
				}, 100);
			}
		},
		// 群管理
		groupManager() {
			this.$refs.readMe.open()
		},

		// 确认退出群聊
		confirmExit() {
			this.$refs.exitPopup.open();
		},

		// 退出群聊
async exitGroup() {
  try {
    let res;
    if (this.isOwn) {
      // 确保云对象已实现 dissolveGroup 方法
      res = await group.dissolveGroup(this.user.userId, { groupId: this.groupId });
    } else {
      res = await group.quitGroup(this.user.userId, { groupId: this.groupId });
    }

    if (res.code === 0) {
      uni.showToast({ title: res.message });
      this.$refs.exitPopup.close(); // 关闭弹窗
      setTimeout(() => uni.navigateBack(), 1500); // 延迟返回，让用户看到提示
    } else {
      uni.showToast({ title: res.message || '操作失败', icon: 'none' });
    }
  } catch (e) {
    console.error('退出/解散群聊失败：', e);
    uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
  }
},
		dialogClose() {
			this.$refs.exitPopup.close();
		}
	}
};
</script>
<style scoped>
/* 成员列表区域 */
.member-list {
	padding: 16px;
	background-color: #fff;
}

/* 成员容器：使用Flex实现自动换行 */
.member-container {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-wrap: wrap;
	gap: 15px; /* 成员之间的间距 */
	margin-bottom: 12px;
}

/* 显示更多按钮的头像样式 */
.more-avatar {
	background-color: #f0f4ff;
	color: #007aff;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 500;
}

/* 显示更多按钮的文本样式（与成员名称一致） */
.member-item .member-name {
	font-size: 12px;
	text-align: center;
	color: #333;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.member-item {
	position: relative;
}
.readMe {
  padding: 20px;
  max-height: 80vh; /* 最大高度为屏幕的 80% */
  overflow-y: auto; /* 内容超出时滚动 */
  background-color: #fff; /* 白色背景（默认可能透明） */
  border-radius: 8px; /* 圆角（优化外观） */
}
.del-icon {
	position: absolute;
	top: 0;
	z-index: 10;
	padding: 3rpx;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	height: 40rpx;
	width: 40rpx;
	background-color: #ff3b30;
}
.avatar {
	width: 50px;
	height: 50px;
	border-radius: 50%;
	overflow: hidden;
	margin: 0 auto 4px;
	background-color: #eee;
}
.avatar image {
	width: 100%;
	height: 100%;
}
.member-name {
	font-size: 12px;
	color: #333;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

/* 添加成员按钮 */
.add-member {
	width: 60px;
	text-align: center;
	align-self: flex-start;
}
.add-icon {
	width: 50px;
	height: 50px;
	border-radius: 50%;
	background-color: #f5f5f5;
	border: 1px dashed #ccc;
	margin: 0 auto 4px;
	line-height: 50px;
	font-size: 24px;
	color: #999;
}
.add-text {
	font-size: 12px;
	color: #999;
}

/* 成员总数 */
.member-count {
	font-size: 12px;
	color: #666;
	margin-top: 8px;
}

/* 群信息区域 */
.group-info {
	margin-top: 12px;
	background-color: #fff;
}
.info-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 14px 16px;
	border-bottom: 1px solid #f5f5f5;
}
.info-label {
	font-size: 15px;
	color: #333;
	width: 70px;
}
.info-value {
	flex: 1;
	font-size: 15px;
	color: #666;
	text-align: right;
}
.notice-value {
	text-align: right;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

/* 功能操作区 */
.function-area {
	display: flex;
	flex-wrap: wrap;
	padding: 16px;
	margin-top: 12px;
	background-color: #fff;
}
.function-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 33.333%;
	margin-bottom: 16px;
	.funtion-item-icon {
		width: 40rpx;
		height: 40rpx;
	}
}
.function-name {
	font-size: 12px;
	color: #666;
	margin-top: 8px;
}

/* 退出按钮 */
.exit-btn {
	width: 90%;
	height: 44px;
	line-height: 44px;
	text-align: center;
	background-color: #fff;
	border: 1px solid #ff3b30;
	color: #ff3b30;
	border-radius: 22px;
	margin: 30px auto;
	font-size: 15px;
}

/* 二维码弹窗 */
.qrcode-popup {
	width: 280px;
	padding: 20px;
	background-color: #fff;
	border-radius: 12px;
	text-align: center;
}
.qrcode-title {
	font-size: 18px;
	color: #333;
	margin-bottom: 16px;
	font-weight: 500;
}
.qrcode-content {
	width: 180px;
	margin: 0 auto;
}
.qrcode-content image {
	width: 100%;
}
.qrcode-desc {
	font-size: 12px;
	color: #666;
	margin-top: 12px;
}
.qrcode-close {
	width: 100%;
	height: 44px;
	line-height: 44px;
	margin-top: 20px;
	border-top: 1px solid #f5f5f5;
	font-size: 15px;
	color: #007aff;
}
</style>
